package com.jcark.ui.widget;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;

import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

public abstract class BaseBottomSheetDialog extends BottomSheetDialogFragment {
    protected boolean isFirstVisible = true;
    protected View rootView;

    /**
     * @return 布局 layout id
     */
    protected abstract int setLayout();

    /**
     * 页面 view / 数据的初始化
     */
    protected abstract void setUp();

    /**
     * 首次进入页面时, 获取数据
     */
    protected abstract void fetchData();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        rootView = setLayout(inflater, container);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (isFirstVisible) {
            setUp();
        }
    }

    /**
     * 初始化页面布局
     * 给 statusLayout 设置各种页面状态 view
     */
    private View setLayout(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(setLayout(), container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstVisible) {
            fetchData();
            isFirstVisible = false;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void show(@NonNull FragmentManager manager, @Nullable String tag) {
        if (isAdded()) {
            manager.beginTransaction().remove(this).commit();
        }
        super.show(manager, tag);
    }
}
